﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccess;
using System.Data;
using System.Data.SqlClient;

namespace Busness
{
    public class SqlErrorCode
    {
        public const int NO_USER = -1;
        public const int PASSWORD_WRONG = 0;

        public const int REGIST_USER_HAS_USER = 0;

        public const int EXECUTE_OK = 0;
        public const int CHANGE_PWD_NO_USER = -1;
        public const int CHANGE_PWD_OLDPWD_WRONG = -2;
    }

    public class ExcuteCommandEventArgs : EventArgs
    {
        public UInt32 UserID;
        public Type _scoketCommandType;
        public object _returnValue;
    }
    public class ExcuteCommandArrayEventArgs : EventArgs
    {
        public string UserID;
        public Type _scoketCommandType;
        public object[] _returnValue;
    }
    public delegate void ExcuteCommandHandler(object sender, ExcuteCommandEventArgs e);
    public delegate void ExcuteCommandArrayHandler(object sender, ExcuteCommandArrayEventArgs e);
    /// <summary>
    /// business 是单例，全局只需要一个该类的实例
    /// </summary>
    public class Business
    {
        public Dictionary<UInt32, DataLinkPool> userDataQuaryMap = new Dictionary<UInt32, DataLinkPool>();
        public event ExcuteCommandHandler ExcuteCommandComplete;
        public event ExcuteCommandArrayHandler ExcuteCommandArrayComplete;
        public bool ExitApplation = false;
        //该类的构造器是私有的，以确保不能在类外实例化
        /// <summary>
        /// 该类不能在类外被实例化，请使用 getIntance() 方法获得该类的实例
        /// </summary>
        private Business()
        {
        }

        public void Init()
        {
            // 给预先创建的线程初始化事件
            // ThreadPool.GetInstance().Creates(4);
        }

        public void Update(float deltaTime)
        {
            ThreadPool.GetInstance().ManageThread();
        }

        private static Business bs;
        public static Business getInstance()
        {
            if (bs == null)
            {
                bs = new Business();
            }
            return bs;
        }
        /// <summary>
        /// 检查密码
        /// </summary>
        public void checkPwd(string userName, string password, ExcuteSqlEventHander complete)
        {
            string commandText = "[dbo].[checkPwd]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] { "@passWord", "@userName" };
            object[] values = new object[] {password, userName };
            object userID = data.executesql(commandText, type, paras, values);
            if (complete != null)
            {
                ExcuteSqlEventArgs args = new ExcuteSqlEventArgs();
                args._returnValue = userID;
                complete(this, args);
            }
        }

        public void registUser(string userName, string password, string nickName, ExcuteSqlEventHander complete)
        {
            string commandText = "[dbo].[createUser]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] { "@password", "@userName", "@dateTime" ,"@niName"};
            object[] values = new object[] { password, userName, DateTime.Now.ToString() ,nickName};
            object userID = data.executesql(commandText, type, paras, values);
            if (complete != null)
            {
                ExcuteSqlEventArgs args = new ExcuteSqlEventArgs();
                args._returnValue = userID;
                complete(this, args);
            }
        }

        public void setRtcData(int areaNo, int drvNo, 
            int t1, int t2, int t3, int t4, int t5, int t6, 
            int a_value, int b_value, int run_mod, int run_ta, 
            ushort[] motherboardID, int a_valueAuto, int b_valveAuto,
            int errNum, int runTime, ExcuteCommandHandler complete)
        {
            string commandText = "[dbo].[setDataToRTC]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] 
            {
               "@AreaNo", "@DrvNo",  "@T1" , "@T2", "@T3" ,"@T4","@T5","T6",
                "@A_Valve", "@B_Valve","@RunMod","@RunTa","@MotherboardID",
                "@createTime", "@A_ValveAuto","@B_ValveAuto","@ErrNum","@RunTime"
            };
            string mid = "";
            for (int i = 0; i < motherboardID.Length; i++)
            {
                if (i < motherboardID.Length - 1)
                {
                    mid += Convert.ToString(motherboardID[i], 16) + "|";
                }
                else
                {
                    mid += Convert.ToString(motherboardID[i], 16);
                }
            }

            object[] values = new object[]
            {
                areaNo, drvNo, t1, t2, t3, t4, t5, t6,
                a_value, b_value, run_mod, run_ta, mid,
                DateTime.Now.ToString(), a_valueAuto, b_valveAuto, errNum, runTime
            };
            object userID = data.executesql(commandText, type, paras, values);
            if (complete != null)
            {
                complete(this, null);
            }
        }

        public int selectSiteId(int DrvId, int AreaNo)
        {
            string commandText = "[dbo].[selectSiteId]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] { "@DrvId", "@AreaId" };
            object[] values = new object[] { DrvId, AreaNo };
            object userID = data.executesql(commandText, type, paras, values);
            return (int)userID;
        }

        public DataSet getRtcData(int areaNo, int drvNo)
        {
            string[] paras = new string[] { "@areaNo", "@drvNo" };
            object[] values = new object[] { areaNo, drvNo };
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectRTCData]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public void setCurveData(int areaNo,int drvId, int name, UInt16[] dn,ExcuteCommandHandler complete)
        {
            string DN = "";
            for (int i = 0; i < dn.Length; i++)
            {
                DN += dn.ToString();
                if (i != dn.Length - 1)
                { 
                    DN += ";";
                }
            }

            string commandText = "[dbo].[setCurveData]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] { "@areaNo","@drvNo", "@name", "@dn", "@createTime" };
            object[] values = new object[] {areaNo, drvId, name, DN, DateTime.Now.ToString()};
            data.executesql(commandText, type, paras, values);
            if (complete != null)
            {
                complete(this, null);
            }
        }

        public void insertArea(int name, int areaNo, int userId, ExcuteCommandHandler complete)
        {
            string commandText = "[dbo].[insertArea]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[] { "@name", "@areaNo", "@userId", "@createTime" };
            object[] values = new object[] { name.ToString(), areaNo, userId, DateTime.Now.ToString() };
            object userID = data.executesql(commandText, type, paras, values);
            if (complete != null)
            {
                complete(this, null);
            }
        }

        public DataSet selectArea(int areaNo, int userId, ExcuteCommandHandler complete)
        {
            string[] paras = new string[] { "@areaNo", "@userId" };
            object[] values = new object[] { areaNo, userId };
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectArea]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public DataSet selectCurves(int areaNo, int drvNo)
        {
            string[] paras = new string[] { "@areaNo","@drvNo" };
            object[] values = new object[] { drvNo , areaNo};
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectCurves]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public DataSet selectTempcorrection(int AreaNo, int DrvNo)
        {
            string[] paras = new string[] { "@AreaNo", "@DrvNo" };
            object[] values = new object[] { AreaNo, DrvNo };
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectTempcorrection]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public DataSet selectValveSetting(int DrvNo, int ValveNo, int AreaNo)
        {
            string[] paras = new string[] { "@DrvNo", "@ValveNo", "@AreaNo" };
            object[] values = new object[] { DrvNo, ValveNo, AreaNo };
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectValveSetting]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public void setSiteData(int AreaNo, int DrvNo, int Name, int userId, byte[] motherboardId, int RunTime, int RunSum)
        {
            string commandText = "[dbo].[setSiteData]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[]
            {
                "@AreaNo","@DrvNo","@Name","@UserId","@createTime","@MotherboardId","@RunTime","@RunSum"
            };
            string mid = "";
            for (int i = 0; i < motherboardId.Length; i++)
            {
                mid += Convert.ToString(motherboardId[i], 16);
            }
            object[] values = new object[]
            {
               AreaNo,DrvNo,Name,userId, DateTime.Now.ToString(),mid,RunTime,RunSum
            };
            object userID = data.executesql(commandText, type, paras, values);
        }

        public void setTempcorrection(int DrvNo, int T1, int T2, int T3, int T4, int T5, int T6, int TStop, int AreaNo)
        {
            string commandText = "[dbo].[setTempcorrection]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[]
            {
                "@DrvNo","@T1","@T2","@T3","@T4","@T5","@T6","@TStop","@AreaNo","@CreateTime"
            };

            object[] values = new object[]
            {
               DrvNo,T1, T2, T3,T4,T5,T6,TStop,AreaNo,DateTime.Now.ToString()
            };
            object userID = data.executesql(commandText, type, paras, values);
        }

        public void setTime(int DrvNo, int CurveNo, int start, int end, int curveId, int spare, int AreaID)
        {
            string commandText = "[dbo].[setTime]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[]
            {
                "@DrvNo", "@CurveNo", "@Start","@End","@CurveId","@Spare","@AreaNo","@CreateTime"
            };

            object[] values = new object[]
            {
               DrvNo, CurveNo, start.ToString(), end.ToString(), curveId, spare, AreaID, DateTime.Now.ToString()
            };
            object userID = data.executesql(commandText, type, paras, values);
        }

        public void setValveSetting(int DrvNo, int ValvaNo, int W1, int W2, int W3, int W4, int W5, int W6, int Max, int Min, int Step, int Delay, int AreaNo)
        {
            string commandText = "[dbo].[setValveSetting]";
            CommandType type = CommandType.StoredProcedure;
            string[] paras = new string[]
            {
                "@DrvNo", "@ValveNo","@W1","@W2","@W3","@W4","@W5","@W6","@Max","@Min","@Step","@Delay","@AreaNo","@CreateTime"
            };

            object[] values = new object[]
            {
                DrvNo, ValvaNo, W1,W2,W3,W4,W5,W6,Max,Min,Step,Delay, AreaNo,DateTime.Now.ToString()
            };
            object userID = data.executesql(commandText, type, paras, values);
        }

        public int[] getAreaNo(int userId)
        {
            string commandText = "[dbo].[selectAreaNo]";

            string[] paras = new string[]
            {
                "@userId"
            };

            object[] values = new object[]
            {
                userId
            };
            DataSet ds = data.GetDataSet(commandText, 0, CommandType.StoredProcedure, paras, values);
            if (ds.Tables == null)
            {
                return new int[] { };
            }
            int[] retValue = new int[ds.Tables[0].Rows.Count];
            
            for (int i = 0; i < retValue.Length; i++)
            {
                retValue[i] = Convert.ToInt32(ds.Tables[0].Rows[i][0]);
            }
            return retValue;
        }

        public string getAreaName(int areaNo)
        {
            string commandText = "[dbo].[selectAreaName]";

            string[] paras = new string[]
            {
                "@AreaNo"
            };

            object[] values = new object[]
            {
                areaNo
            };
            object[] areaNames = data.GetValues(commandText, CommandType.StoredProcedure, paras, values, SqlDbType.Int);
            if (areaNames == null)
                return "";
            if (areaNames.Length == 0)
            {
                return "";
            }
            return areaNames[0].ToString();
        }

        public string getSiteName(int areaNo, int drvNo)
        {
            string commandText = "[dbo].[selectSiteName]";

            string[] paras = new string[]
            {
                "@AreaNo", "@DrvNo"
            };

            object[] values = new object[]
            {
                areaNo, drvNo
            };
            object[] siteNames = data.GetValues(commandText, CommandType.StoredProcedure, paras, values, SqlDbType.Int);
            if (siteNames == null)
                return "";
            if (siteNames.Length == 0)
            {
                return "";
            }
            return siteNames[0].ToString();
        }

        public DataSet getTime(int DrvNo, int AreaNo)
        {
            string[] paras = new string[] { "@DrvNo", "@AreaNo" };
            object[] values = new object[] { DrvNo, AreaNo };
            DataSet ds = new DataSet();
            ds = data.GetDataSet("[dbo].[selectTime]", 0, CommandType.StoredProcedure, paras, values);
            return ds;
        }

        public int[] getDeviceId(int userId, int areaNo)
        {
            string commandText = "[dbo].[selectDeviceNo]";

            string[] paras = new string[]
            {
                "@userId", "@AreaNo"
            };

            object[] values = new object[]
            {
                userId, areaNo
            };
            DataSet ds = data.GetDataSet(commandText,0, CommandType.StoredProcedure, paras, values);
            int[] retValue = new int[ds.Tables[0].Rows.Count];
            for (int i = 0; i < retValue.Length; i++)
            {
                retValue[i] = Convert.ToInt32(ds.Tables[0].Rows[i][0]);
            }
            return retValue;
        }

        public int getUserId(int AreaNo, int DrvNo)
        {
            string commandText = "[dbo].[selectUserId]";

            string[] paras = new string[]
            {
                "@DrvNo", "@AreaNo"
            };

            object[] values = new object[]
            {
                DrvNo, AreaNo
            };
            object[] retValue = data.GetValues(commandText, CommandType.StoredProcedure, paras, values, SqlDbType.Int);
            if (retValue == null)
            {
                return 0;
            }
            if (retValue.Length > 0)
            {
                return Convert.ToInt32(retValue[0]);
            }
            return 0;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        public void changePwd(string pwd, string oldpwd, UInt32 userID, ExcuteSqlEventHander complete)
        {
            //DataAccess.BaseParamter norm4 = new DataAccess.BaseParamter();
            //norm4.commandText = "CheckPassword";
            //norm4.commandType = CommandType.StoredProcedure;
            //norm4.paras = new string[] { "@passWord", "@usrName" };
            //norm4.values = new object[] { password, userName };
            //norm4._procedureType = ProcedureType.EXCUTE_SQL_4_PARAM;
            //norm4.completeEvent = complete;
            //ThreadPool.GetInstance().HandleDataLink(0, norm4); // 所有登录排队 
        }
    }
}
